package cn.com.lms.business.examRewrite.service;

import cn.com.lms.business.core.util.SystemUserUtil;
import cn.com.lms.business.examRewrite.persistence.entity.ExerciseReWrite;
import cn.com.lms.business.examRewrite.persistence.entity.ExerciseReWriteVo;
import cn.com.lms.business.examRewrite.persistence.repository.ExerciseReWriteDao;
import cn.com.lms.business.user.persistence.entity.SysUserVo;
import com.bnzj.core.persistence.BaseService;
import com.bnzj.core.persistence.query.QueryHelpBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@Service
public class ExerciseReWriteService extends BaseService<ExerciseReWriteDao, ExerciseReWrite, Long> {
    @Autowired
    ExerciseQuestionReWriteService exerciseQuestionReWriteService;

    @Autowired
    ExerciseEmployeeReWriteVoService exerciseEmployeeReWriteVoService;



    public static QueryHelpBean getQueryHelpBean() {
        String baseSQL = "SELECT ee.*,(SELECT count(*) FROM bnz_exam_question_subject WHERE is_delete = 0 AND question_id" +
                " IN " +
                "(SELECT question_id FROM bnz_exam_exercise_question eq  WHERE ee.id = eq.exercise_id)) count";
        String whereSQL = " from bnz_exam_exercise ee where 1=1 ";
        QueryHelpBean queryHelpBean = new QueryHelpBean(baseSQL+whereSQL,"select count(1)" + whereSQL, ExerciseReWriteVo.class);
        return queryHelpBean;
    }

    /**
     * 更新数据
     * @param exerciseReWriteData
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateExercise(ExerciseReWrite exerciseReWriteData) {
        // 保存 bnz_exam_exercise的数据
        save(exerciseReWriteData);

        // 保存 bnz_exam_exercise_question
        exerciseQuestionReWriteService.batchSave(exerciseReWriteData);

        // 保存 bnz_exam_exercise_employees
        exerciseEmployeeReWriteVoService.batchSave(exerciseReWriteData);

    }

    /**
     * 启用
     * @param result
     * @param id
     * @return
     */
    public int enableById(Boolean result, List<Long> id) {
        return repository.enableById(result,id);
    }

    /**
     * 禁用
     * @param result
     * @param id
     * @return
     */
    public int disableById(Boolean result, List<Long> id) {
        return repository.disableById(result,id);
    }

    /**
     * 删除、批量删除
     * @param result
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Integer deletesById(boolean result, List<Long> id) {
        // 删除 bnz_exam_employee
        exerciseEmployeeReWriteVoService.deleteSByExerciseId(result,id);
        // 删除 bnz_exam_question
        exerciseQuestionReWriteService.deleteSByExerciseId(result,id);
        // 删除 bnz_exam_exercise
        return repository.deletesById(result,id);
    }

    /**
     * 判断名称、科目、人员、创建人是否同时为true
     * @param exerciseReWrite
     * @return
     */
    public Boolean Allequal(ExerciseReWrite exerciseReWrite) {
        AtomicReference<Boolean> result = new AtomicReference<>(true);
        // 判断名字和创建人是否已存在
        SysUserVo currentUser = SystemUserUtil.getCurrentUser();
        List<ExerciseReWrite> exerciseReWrites = repository.getExerciseReWritesByNameAndCreator(exerciseReWrite.getExerciseName(), currentUser.getId());
        if (exerciseReWrites==null && exerciseReWrites.size()==0){
            result.set(false);
            return result.get();
        }else {
            // 获取questionIds集合
            List<Long> questionIdsData = exerciseReWrite.getExerciseQuestionList().stream().map(item -> item.getQuestionId()).collect(Collectors.toList());
            exerciseReWrites.stream().forEach(item->{
                // 获取数据库对于的获取questionIds集合
                List<Long> qe_ids = exerciseQuestionReWriteService.getQuestionIdByExerciseId(item.getId());
                if (qe_ids!=null&&qe_ids.size()>0&&qe_ids.size()==questionIdsData.size()){
                    // 判断两个集合的元素是否相同
                    boolean same = this.elementsSame(qe_ids, questionIdsData);
                    if (same){
                        result.set(true);
                        // 相同
                        // 获取人员
                        List<Long> employeeIds = exerciseReWrite.getExerciseEmployeeList().stream().map(employee -> employee.getEmployeeId()).collect(Collectors.toList());
                        // 获取数据库对于的获取employeeIds集合
                        List<Long> em_ids = exerciseEmployeeReWriteVoService.getEmployeexByExerciseId(item.getId());
                        if (em_ids!=null&&em_ids.size()>0&&em_ids.size()==employeeIds.size()){
                            // 判断两个集合的元素是否相同
                            boolean sames = this.elementsSame(em_ids, employeeIds);
                            if (sames){
                                result.set(true);
                            }else{
                                result.set(false);
                            }
                        }else {
                            result.set(false);
                        }
                    }else {
                        result.set(false);
                    }
                }else {
                    result.set(false);
                }
            });
        }
        return result.get();
    }

    /**
     * 判断两个集合是否相同
     * @param ids
     * @param questionIdsData
     * @return
     */
    private boolean elementsSame(List<Long> ids, List<Long> questionIdsData) {
        return ids.containsAll(questionIdsData);
    }

    /**
     * 新增数据
     * @param exerciseReWrite
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveExercise(ExerciseReWrite exerciseReWrite) {
        // 保存名 bnz_exam_exercise
        SysUserVo currentUser = SystemUserUtil.getCurrentUser();
        exerciseReWrite.setIsDelete(false);
        exerciseReWrite.setIsEnable(true);
        exerciseReWrite.setCreator(String.valueOf(currentUser.getId()));
        exerciseReWrite.setCreateTime(new Date());
        exerciseReWrite.setCreatorName(currentUser.getCname());
        save(exerciseReWrite);
        // 保存人员 bnz_exam_Exercise_employee
        exerciseEmployeeReWriteVoService.batchSave(exerciseReWrite);
        // 保存科目 bnz_exam_exercise_question
        exerciseQuestionReWriteService.batchSave(exerciseReWrite);

    }
}
